import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Radio,
  RadioGroup,
  RangePicker,
  Select,
  SelectOption,
  Space,
  Spin
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { commonApi, commonMenuApi, jindouGiftApi } from '@/apis'
import { JindouGiftGoodsItem } from '@/apis/jindouGiftTypes'
import { ProEditor, ProEditorProps, ProEditorRef } from '@/components'
import UploadFile from '@/components/UploadFile'
import { FILE_TYPE } from '@/components/UploadFile/types'
import { useBack } from '@/hooks'

export default defineComponent({
  name: 'JdgAddOrEditGoods',
  setup() {
    const { handleCancel } = useBack('refreshJdgGoodsList')

    const loading = ref(false)
    const route = useRoute()
    const goodsData = ref({} as JindouGiftGoodsItem)
    const selectCouponsList = ref([] as any[])
    const selectLabelList = ref([] as any[])

    const goodsTypeOptions = [
      { label: '单个app优惠券', value: 0 },
      { label: '券包', value: 1 }
    ]

    const submitLoading = ref(false)
    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '300px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data

              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)

    onMounted(() => {
      getCouponsAndLabelList()
    })

    //获取优惠券和标签
    async function getCouponsAndLabelList() {
      try {
        loading.value = true
        selectCouponsList.value = await jindouGiftApi.getJindouGiftCouponList()
        selectLabelList.value = await commonMenuApi.getSelectLabelList()
        console.log(selectLabelList.value)
        loading.value = false
        init()
      } catch {
        handleCancel()
      }
    }

    //初始化
    function init() {
      if (route.query.id) {
        getDetail()
      } else {
        editorConfig.value.editorVisible = true
        goodsData.value.goodsProperty = 0
        goodsData.value.goodsType = 0
        goodsData.value.couponsTemp = []
        goodsData.value.labels = []
        goodsData.value.status = 1
      }
    }

    //获取详情
    async function getDetail() {
      try {
        loading.value = true
        const data = await jindouGiftApi.getGoodsDetail(route.query.id)
        editorConfig.value.editorHtml = data.description
        editorConfig.value.editorVisible = true
        if (data.coupons) {
          data.couponsTemp = data.coupons.map(item => item.id)
        } else {
          data.couponsTemp = []
        }
        if (data.labels) {
          data.labels = data.labels.map(item => item.id)
        } else {
          data.labels = []
        }
        Object.assign(goodsData.value, data)
        loading.value = false
      } catch (e) {
        handleCancel()
      }
    }

    //确定
    async function confirm() {
      if (
        !goodsData.value.couponsTemp ||
        goodsData.value.couponsTemp.length == 0
      ) {
        message.error('请选择优惠券')
        return
      }
      goodsData.value.coupons = []
      for (const label of goodsData.value.couponsTemp) {
        const coupun: any = selectCouponsList.value.find(
          item => label == item.id
        )
        goodsData.value.coupons.push({ id: coupun.id, name: coupun.name })
      }
      if (!goodsData.value.name) {
        message.error('请输入商品主标题')
        return
      }
      if (!goodsData.value.mainImg) {
        message.error('请上传商品主图')
        return
      }
      goodsData.value.description = editorRef.value.editor.getHtml()
      if (!goodsData.value.marketPrice) {
        message.error('请输入市场价')
        return
      }
      if (!goodsData.value.salePrice || !goodsData.value.saleGold) {
        message.error('请输入销售价')
        return
      }
      if (!goodsData.value.saleNum && goodsData.value.saleNum !== 0) {
        message.error('请输入虚拟销量')
        return
      }
      try {
        submitLoading.value = true
        if (goodsData.value.id) {
          await jindouGiftApi.editGoods(goodsData.value)
        } else {
          await jindouGiftApi.addGoods(goodsData.value)
        }
        handleCancel()
      } finally {
        submitLoading.value = false
      }
    }

    //标签改变
    function onLabelChange(labels: string[]) {
      if (labels.length > 3) {
        labels.shift()
        goodsData.value.labels = labels
      }
    }

    //优惠券改变
    function onCouponChange(labels: string[]) {
      if (labels.length > 0) {
        if (goodsData.value.goodsType == 0 && labels.length > 1) {
          goodsData.value.couponsTemp = [labels.pop()]
        }
        const selectedCoupons = [] as any[]
        for (const label of labels) {
          selectedCoupons.push(
            selectCouponsList.value.find(item => label == item.id)
          )
        }
        let minStock = 10000000
        for (const item of selectedCoupons) {
          if (item.stock < minStock) {
            minStock = item.stock
          }
        }
        goodsData.value.stock = minStock
      } else {
        goodsData.value.stock = 0
      }
    }

    return {
      loading,
      goodsData,
      editorRef,
      editorConfig,
      submitLoading,
      goodsTypeOptions,
      selectCouponsList,
      selectLabelList,
      onLabelChange,
      onCouponChange,
      confirm,
      handleCancel
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <h3 style={{ marginLeft: '30px' }}>
            {this.$route.query.id ? '编辑商品' : '新增商品'}
          </h3>
          <Form labelCol={{ span: 2 }}>
            <FormItem label="商品类型" required>
              <RadioGroup
                v-model:value={this.goodsData.goodsType}
                onChange={() => {
                  this.onCouponChange(this.goodsData.couponsTemp)
                }}
              >
                {this.goodsTypeOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            <FormItem label="商品属性" required>
              <Radio checked>{'虚拟物品'}</Radio>
            </FormItem>
            <FormItem label="优惠券" required>
              <Select
                mode="multiple"
                onChange={this.onCouponChange}
                placeholder="请选择"
                v-model:value={this.goodsData.couponsTemp}
                style={{ width: '300px' }}
              >
                {this.selectCouponsList.map(val => (
                  <SelectOption value={val.id}>{val.name}</SelectOption>
                ))}
              </Select>
            </FormItem>
            <FormItem label="库存" required>
              <InputNumber
                v-model:value={this.goodsData.stock}
                min={0}
                maxlength={10}
                disabled
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="商品主标题" required>
              <Input
                maxlength={60}
                v-model:value={this.goodsData.name}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="商品副标题">
              <Input
                maxlength={60}
                v-model:value={this.goodsData.subTitle}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="商品主图" required>
              <UploadFile v-model={[this.goodsData.mainImg, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label="商品轮播图">
              <UploadFile
                maxLength={5}
                v-model={[this.goodsData.banner, 'urls']}
              >
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label="商品视频">
              <div style={{ width: '400px' }}>
                <UploadFile
                  fileType={FILE_TYPE.VIDEO}
                  UploadFile
                  v-model={[this.goodsData.video, 'urls']}
                >
                  <Button>上传视频</Button>
                </UploadFile>
              </div>
            </FormItem>
            <FormItem label="商品详情信息">
              <ProEditor ref="editorRef" {...this.editorConfig} />
            </FormItem>
            <FormItem label="市场价" required>
              <InputNumber
                placeholder="请输入"
                v-model:value={this.goodsData.marketPrice}
                min={0}
                precision={2}
                maxlength={10}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="销售价" required>
              <Space>
                {'现金'}
                <InputNumber
                  placeholder="请输入"
                  v-model:value={this.goodsData.salePrice}
                  min={0}
                  precision={2}
                  maxlength={10}
                  style={{ width: '120px' }}
                />
                {'元  +  金豆'}
                <InputNumber
                  placeholder="请输入"
                  v-model:value={this.goodsData.saleGold}
                  min={0}
                  precision={2}
                  maxlength={10}
                  style={{ width: '120px' }}
                />
              </Space>
            </FormItem>
            <FormItem label="虚拟销量" required>
              <InputNumber
                placeholder="请输入"
                v-model:value={this.goodsData.saleNum}
                min={0}
                maxlength={10}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="设置标签">
              <Select
                mode="multiple"
                maxTagCount={3}
                v-model:value={this.goodsData.labels}
                style={{ width: '300px' }}
                placeholder="请选择"
                onChange={this.onLabelChange}
              >
                {this.selectLabelList.map(val => (
                  <SelectOption value={val.id}>{val.labelName}</SelectOption>
                ))}
              </Select>
            </FormItem>
            <FormItem label="状态：" required>
              <RadioGroup v-model:value={this.goodsData.status}>
                <Radio value={1}>上架</Radio>
                <Radio value={0}>下架</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                loading={this.submitLoading}
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.confirm}
              >
                确定
              </Button>
            </FormItem>
          </Form>
        </Spin>
      </div>
    )
  }
})
